$(function () {
    $(document).keyup(function (e) {
        var keycode = e.keyCode;
        if (keycode == 13) {
            $("#btnSearch").click();
        }
    });

    $(document).delegate("#btnSearch", "click", function () {
        reflashTable();
    });
});


//角色列表===========================================================================================================


function initRoleTable() {
    var url = "/manage/role/list";
    $('#table').bootstrapTable({
        url: url,
        striped: true,
        cache: false,
        pagination: true,
        sidePagination: "server",
        toolbar: "#toolbar",
        pageList: [10, 25, 50, 100],
        columns: [{
            checkbox: true,
            align: 'center',
        }, {
            field: 'roleId',
            title: '角色 ID'
        }, {
            field: 'roleName',
            title: '角色名称'
        }, {
            field: 'remark',
            title: '备注'
        }, {
            field: 'areaName',
            title: '所属地域'
        }, {
            field: 'roleId',
            title: '操作',
            formatter: function (value, row) {
                var result = "";
                result += "<a href='javascript:Base.dialogIframe(\"角色查看\" ,\"/manage/role/view/@roleId\")' class='btn btn-xs'><span class='glyphicon glyphicon-info-sign'></span> 查看</a>";
                result += "<a href='javascript:Base.dialogIframe(\"角色编辑\" ,\"/manage/role/modify/@roleId\")' class='btn btn-xs'><span class='glyphicon glyphicon-pencil'></span> 编辑</a>";
                result += "<a href='javascript:roleDeleteDialog(\"@roleId\", \"@roleName\")' class='btn btn-xs text-danger'><span class='glyphicon glyphicon-remove'></span> 删除</a>";
                result += "<a href='javascript:roleFuncConfig(\"@roleId\")' class='btn btn-xs'><span class='iconfont icon-shejishi'></span> 功能配置</a>";

                result = result.replace(/@roleId/g, value);
                result = result.replace(/@roleName/g, row.roleName);

                return result;
            }
        }],
        responseHandler: function (res) {
            return res.data;
        },
        queryParams: function (params) {
            var searchkey = $.trim($("#searchkey").val());
            var temp = {
                pageSize: params.limit,
                pageNum: (params.offset / params.limit) + 1,
                sort: params.sort,
                searchkey: searchkey
            };
            return temp;
        },
    });
}

function reflashTable() {
    $("#table").bootstrapTable('refresh');
}

function roleDeleteDialog(roleId, roleName) {
    BootstrapDialog.show({
        title: '删除确认',
        message: '请再次确认是否删除角色【' + roleName + '】',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                roleDelete(roleId);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function exportDialog() {
    BootstrapDialog.show({
        title: '导出确认',
        message: '请再次确认是否进行导出操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                var searchkey = $.trim($("#searchkey").val());
                var status = $("#status").val();
                var param = {
                    searchkey: searchkey,
                    status: status
                };
                Base.executeExport("/manage/role/export", param);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}


//角色新增修改===========================================================================================================


function initRoleAddPage() {
    initBootstrapValidator(roleAdd);

    queryFuncs();
}

function initUserModifyPage() {
    initBootstrapValidator(roleModify, "modify");
}

function initBootstrapValidator(submitFunc, type) {
    var option = {
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            roleId: {
                message: '角色名验证失败',
                validators: {
                    notEmpty: {
                        message: '角色ID不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: '角色名长度必须在6到30之间'
                    },
                    threshold: 6, //有6字符以上才发送ajax请求
                    remote: { //{"valid",true}代表有效，{"valid",false}代表无效，
                        url: '/manage/role/checkexist',
                        message: '角色已存在',
                        delay: 2000,
                        type: 'POST'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '角色名由数字字母下划线和.组成'
                    }
                }
            },
            roleName: {
                validators: {
                    notEmpty: {
                        message: '角色名称不能为空'
                    }
                }
            }
        }
    };

    if (type == "modify") {
        delete option.fields.roleId;
    }

    $('form').bootstrapValidator(option).on('success.form.bv', function (e) {
        e.preventDefault();
        submitFunc();
    });

    $('#resetBtn').click(function () {
        $('form').data('bootstrapValidator').resetForm(true);
    });
}

function initFuncs(data) {
    var zNodes = data;
    if (true) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "func") {
                z.name = '<i class="iconfont icon-shejishi"></i> ' + z.name;
            }
        }
    }
    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false,
            addDiyDom: addDiyDom
        },
        check: {
            enable: true,
            chkboxType: {
                "Y": "",
                "N": ""
            }
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: function (event, treeId, treeNode) {
                $("#funcCheckNum").html(ztree_func.getCheckedNodes(true).length);

                var tId = treeNode.tId;
                if (treeNode.checked) {
                    $('input[tId=' + tId + ']').prop("checked", true);
                } else {
                    $('input[tId=' + tId + ']').prop("checked", false);
                }
            }
        }
    };

    ztree_func = $.fn.zTree.init($("#funcTree"), setting, zNodes);
    hideLoading("#funcTree");
}

function addDiyDom(treeId, treeNode) {
    var _o = $("#" + treeNode.tId);

    var str = '<div class="oper-box">';
    str += '<label><input type="checkbox" name="add" tId="@tId" id="add_@id" @pAdd>新增</label>';
    str += '<label><input type="checkbox" name="modify" tId="@tId" id="modify_@id" @pModify>修改</label>';
    str += '<label><input type="checkbox" name="delete" tId="@tId" id="delete_@id" @pDelete>删除</label>';
    str += '<label><input type="checkbox" name="upload" tId="@tId" id="upload_@id" @pUpload>导入</label>';
    str += '<label><input type="checkbox" name="download" tId="@tId" id="download_@id" @pDownload>导出</label>';
    str += '</div>';

    str = str.replace(/@tId/g, treeNode.tId);
    str = str.replace(/@id/g, treeNode.id);
    str = str.replace(/@pAdd/g, treeNode.pAdd === "true" ? "checked" : "");
    str = str.replace(/@pModify/g, treeNode.pModify === "true" ? "checked" : "");
    str = str.replace(/@pDelete/g, treeNode.pDelete === "true" ? "checked" : "");
    str = str.replace(/@pUpload/g, treeNode.pUpload === "true" ? "checked" : "");
    str = str.replace(/@pDownload/g, treeNode.pDownload === "true" ? "checked" : "");
    _o.append(str);
}

function roleFuncConfig(roleId) {
    roleFuncConfigDialog = BootstrapDialog.show({
        title: '角色配置',
        message: $("<p class='alert alert-info manage-role-func-dialog'>共<span id='funcTotalNum' class='label label-primary'>0</span>个功能，已分配<span id='funcSelNum' class='label label-primary'>0</span>个，目前已选中<span id='funcCheckNum' class='label label-danger csp' onclick='openCheckZode()'>0</span>个</p><div id='funcTree' class='ztree loading' style='max-height:400px; overflow: auto;'></div>"),
        type: BootstrapDialog.TYPE_PRIMARY,
        buttons: [{
            label: '确定',
            cssClass: 'btn-primary',
            action: function (dialog) {
                saveRoleFunc(roleId);
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }],
        onshown: function () {
            queryRoleFuncs(roleId);
        }
    });
}

/**
 * 展开选中的节点
 */
function openCheckZode() {
    var nodes = ztree_func.getCheckedNodes(true);

    var ns = [];
    for (var i = nodes.length - 1; i >= 0; i--) {
        ns = ns.concat(nodes[i].getPath());
    }
    for (var i = ns.length - 1; i >= 0; i--) {
        ztree_func.expandNode(ns[i], true, false, true);
    }
}


//ajax提交===========================================================================================================


function roleAdd() {
    var data = $('form').serializej();

    var funcs = getCheckedFuncs();
    data["funcs"] = funcs;

    Base.ajax({
        "url": "/manage/role/add",
        "data": data,
        "success": function (data) {
            if (data.code) {
                tipsuccess("角色新增成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("角色新增失败！");
            }
        }
    });
}
function roleModify() {
    var data = $('form').serializej();

    Base.ajax({
        "url": "/manage/role/modify",
        "data": data,
        "success": function (data) {
            if (data.code) {
                tipsuccess("角色修改成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("角色修改失败！");
            }
        }
    });
}

function roleDelete(roleId, roleName) {
    Base.ajax({
        "url": "/manage/role/delete",
        "data": {
            "roleId": roleId
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("角色删除成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("角色删除失败！");
            }
        }
    });
}

function queryRoleFuncs(roleId) {
    Base.ajax({
        "url": "/manage/role/funcs/" + roleId,
        "async": false,
        "success": function (data) {
            if (data.code) {
                initFuncs(data.data.funcs);
                $("#funcTotalNum").html(data.data.funcTotalNum);
                $("#funcSelNum").html(data.data.funcSelNum);
                $("#funcCheckNum").html(data.data.funcSelNum);
            } else {
                tiperror("初始化功能信息失败，请刷新页面！");
            }
        }
    });
}

function queryFuncs() {
    Base.ajax({
        "url": "/manage/role/funcs",
        "success": function (data) {
            if (data.code) {
                initFuncs(data.data.funcs);
                $("#funcTotalNum").html(data.data.funcTotalNum);
            } else {
                tiperror("初始化功能信息失败，请刷新页面！");
            }
        }
    });
}

function saveRoleFunc(roleId) {
    var funcs = getCheckedFuncs();

    var data = {
        roles: roleId,
        funcs: funcs
    };

    Base.ajax({
        "url": "/manage/role/save/rolefunc",
        "async": false,
        "data": data,
        "success": function (data) {
            if (data.code) {
                tipsuccess("保存成功");
                roleFuncConfigDialog.close();
                reflashTable();
            } else {
                tiperror("保存失败");
            }
        }
    });
}

function getCheckedFuncs() {
    var nodes = ztree_func.getCheckedNodes(true);

    var fId = [];
    for (var i = nodes.length - 1; i >= 0; i--) {
        var f = nodes[i];
        if (f.type == "func") {
            var id = f.id;
            var flagAdd = $("#add_" + id).is(":checked");
            var flagModify = $("#modify_" + id).is(":checked");
            var flagDelete = $("#delete_" + id).is(":checked");
            var flagUpload = $("#upload_" + id).is(":checked");
            var flagDownload = $("#download_" + id).is(":checked");
            id += "," + flagAdd;
            id += "," + flagModify;
            id += "," + flagDelete;
            id += "," + flagUpload;
            id += "," + flagDownload;
            fId.push(id);
        }
    }

    return fId.join(";");
}

